import { reactive } from 'vue';
import { defineStore } from 'pinia';
import { TypeAppState } from '../common/types';
import * as Dao from '@/common/dao';

const TagRegex = /#[\u4e00-\u9fa5a-zA-Z0-9_\-]+/g
const TagRegex2 = /^#[\u4e00-\u9fa5a-zA-Z0-9_\-]+$/

function extractTags(text : string) {
	// 匹配所有以#开头，后跟中英文数字的连续字符序列
	const matches = text.match(TagRegex) || [];

	// 过滤结果：长度≤10且内容不包含符号
	return matches.filter(tag =>
		tag.length <= 10 &&
		// 二次验证内容部分（不含#）仅含中英文数字
		TagRegex2.test(tag)).map(tag => tag.slice(1));
}

export const useAppStore = defineStore('app', () => {
	const state : TypeAppState = reactive({
		title: 'untitled',
		fileName: '',
		createdAt: new Date(1, 0, 1),
		eventsCount: 100,
		pageIndex: 1,
		pageSize: 500,
		pageCount: 1,
		dateRange: {
			begin: 10101,
			end: 99991231
		},
		groups: {},
		events: [],
		loaded: false
	})


	// 刷新文档
	function loadEvents(pageIndex : Number, pageSize : Number = 500, keywords : string = null) {
		uni.showLoading({
			title: '加载中……'
		})
		Dao.loadEvents(pageIndex, pageSize, keywords);
	}

	// 注册通讯（插件postMsg，仅为动态更新）
	window.addEventListener('message', event => {
		const { cmd, data } = event.data;
		console.log('onmessage', cmd, data)
		switch (cmd) {
			case 'loaded':
				updateDocument(data);
				break;
		}
	})


	function updateDocument(doc : TypeAppState) {

		// 构造标签tags 和 shortContent
		const evts = doc.events.map(e => {
			e.tags = extractTags(e.content)
			return e;
		});

		state.events = doc.events;
		state.title = doc.title;
		state.createdAt = doc.createdAt;
		state.dateRange = doc.dateRange;
		state.eventsCount = doc.eventsCount;
		state.fileName = doc.fileName;
		state.groups = doc.groups;
		state.pageIndex = doc.pageIndex;
		state.pageSize = doc.pageSize;
		state.pageCount = doc.pageCount;
		state.loaded = true;
		uni.hideLoading()
		Dao.showMsg('页面已刷新')

		if (doc.scrollTo > 0) {
			const evtId = `evt-${doc.scrollTo}`;
			retry = 10;
			focusEvent(evtId);
		} 

	}

	return {
		state,
		loadEvents,
	}
});

let retry = 10;
function focusEvent(evtId : string) {
	setTimeout(() => {
		const el = document.getElementById(evtId);
		if (el) {
			el.scrollIntoView({
				behavior: 'smooth' // 平滑滚动效果
			});
		} else {
			retry -= 1;
			if (retry >= 0) {
				focusEvent(evtId);
			}
		}
	}, 500)
}